<?php


namespace app\wechat\controller;

use app\common\model\IntegralModel;
use app\common\model\ProjectModel;
use app\common\model\UserModel;
use app\common\model\MsgModel;
use mg_api\Mg_api;
use think\Controller;
use think\Db;
use think\Loader;
use wechat\wechatCallbackapiTest;


class Index extends Controller
{

    public function __construct()
    {
        Loader::import('wechat.wechatCallbackapiTest');
    }

    //微信自动回复验证token
    public function v_token(){
        $wxapi = new wechatCallbackapiTest();
        $wxapi->responseMsg();
    }
    //获取微信用户
    public function getuser_all(){
        $wxapi = new wechatCallbackapiTest();
        $wxapi->getuser_all();
    }



    public function ee(){
        Db::table('dx_logo')->insert([
            'title'=>"3333",
            'description'=>date("Y-m-d H:i:s",time()),
        ]);
    }
    public static function eee(){
        Db::table('dx_logo')->insert([
            'title'=>"3333",
            'description'=>date("Y-m-d H:i:s",time()),
        ]);
    }


    public function curl_wechat($url, $data)
    {

        //初始化
        $ch = curl_init();
        //设置请求地址
        curl_setopt($ch, CURLOPT_URL, $url);
        //捕获内容但不输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //模拟post发送
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        //执行
        $re = curl_exec($ch);

        //判断是否发送成功
        if ($re == false) {
            echo curl_error($ch);
        } else {
            return $re;
        }
        //关闭
        curl_close($ch);
    }

    //获取积分状态
    public static function get_integral_status()
    {
        //获取所有用户
        $users = UserModel::where('is_pass', '1')->select();
        if ($users) {
            //获取此用户下的项目
            $mg_api = new Mg_api();
            foreach ($users as $k => $v) {
                $user_pro = UserModel::find($v->user_id)->project;
                if ($user_pro) {
                    foreach ($user_pro as $key => $item) {
                        $data = [
                            'key' => 'Get_LinkMan_PointListbyProJect',
                            'wx_openid' => $v->openid,
                            'address' => $item->address,
                        ];
                        $integral = $mg_api->api($data);
                        $integral = json_decode($integral, true);

                        //去除为空的
                        if ($integral['JData']) {
                            foreach ($integral['JData'] as $k_i => $v_i) {
                                //查询能否查到
                                $is_cunzai = IntegralModel::where('address', $v_i['address'])
                                    ->where('point', $v_i['point'])
                                    ->where('sysdate', $v_i['sysdate'])
                                    ->find();
                                if ($is_cunzai) {
                                  // echo $is_cunzai->address . '存在<br/>';
                                } else {
                                    var_dump($v_i);
                                    echo $v_i['address'].'<br>';
                                    IntegralModel::create([
                                        'user_id' => (int)$v->user_id,
                                        'is_send' => 0,
                                        'address' => $v_i['address'],
                                        'point' => $v_i['point'],
                                        'sysdate' => $v_i['sysdate'],
                                        'created_at' => time(),
                                        'is_look' => 0
                                    ]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    //获取本地数据库项目状态

    public static function get_data_status()
    {

        //获取所有用户
        $users = UserModel::where('is_pass', '1')->select();
        //查询每个用户的项目
        if ($users) {
            $mg_api = new Mg_api();
            foreach ($users as $k => $v) {
                if (!empty($v->openid)) {

                    $data = [
                        'key' => 'Get_Project_List',
                        'wx_openid' => $v->openid,
                        'types' => '全部',
                    ];
                    $projects = $mg_api->api($data);
                    $projects = json_decode($projects, true);

                    if ($projects['JData']) {
                        //  dump($projects['JData']);
                        foreach ($projects['JData'] as $key => $item) {
                            if ($item['address']) {
                                $re = ProjectModel::where('address', $item['address'])->find();
                                if ($re) {
                                    // 当次项目在本地数据库存在
                                    //  echo $re->prostatus;
                                    if ($re->prostatus != $item['prostatus'] || $re->linkstatus != $item['linkstatus']) {
                                      //  echo $re->address . '状态有变化<br/>';
                                        //有变化需要更新
                                        ProjectModel::where('address', $item['address'])->update([
                                            'prostatus' => $item['prostatus'],
                                            'linkstatus' => $item['linkstatus'],
                                            'is_look' => '0',
                                            'is_send' => 0

                                        ]);

                                    }
                                } else {
                                    //不存在时插入数据库
                                    ProjectModel::create([
                                        'address' => $item['address']??"",
                                        'user_id' => (int)$v->user_id,
                                        'is_send' => 0,
                                        'prostatus' => $item['prostatus']??"",
                                        'linkstatus' => $item['linkstatus']??"",
                                        'sysdate' => $item['date']??"",
                                        'is_look' => '0',
                                        'created_at' => time()
                                    ]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
        //定时执行入口
    public static function index()
    {
        ini_set('max_execution_time',0);
        //获取项目状态
      $e1 = microtime(true);
        Index::get_data_status();
        $e2 = microtime(true);
        echo '耗时'.round($e2-$e1,3).'秒<br>';
        //获取积极状态
        $t1 = microtime(true);
        Index::get_integral_status();
        $t2 = microtime(true);
        echo '耗时'.round($t2-$t1,3).'秒<br>';

        //发送项目状态更新
		Index::send_product();
        //发送积分
        Index::send_integral();
    }
    //更新用户的信息
    public static function update_user(){
        $users = UserModel::where('is_pass',1)->select();
        if($users){
            $mg_api = new Mg_api();
            foreach($users as $k=>$v){
                $data = [
                    'key' => 'Get_LinkMan',
                    'wx_openid' => $v->openid,
                ];
                $user_data = $mg_api->api($data);
                $user_data = json_decode($user_data, true);
                if($user_data['Status']){
                    //更新
                    $re = UserModel::where('openid',$v->openid)->update([
                        'user_name'=>$user_data['JData'][0]['f_name'],
                        'user_tel'=>$user_data['JData'][0]['f_tel'],
                        'position'=>$user_data['JData'][0]['f_gw'],
                        'user_sex'=>$user_data['JData'][0]['f_name']=='男'?1:0,
                        'company_id'=>$user_data['JData'][0]['f_intermediaryid'],
                        'companyname'=>$user_data['JData'][0]['f_companyname'],
                    ]);
                    var_dump($re);




                }
            }
        }
    }
    public function test(){
        $mg_api = new Mg_api();
        $data = [
            'key' => 'Get_LinkMan',
            'wx_openid' => 'o2ztkxFgZ2MAn7arOwZa4TzjUtFY',
        ];
        $user_data = $mg_api->api($data);
        $user_data = json_decode($user_data, true);
        var_dump($user_data);

    }

    //项目状态信息更新 发送

    public static function send_product(){
       $project =  ProjectModel::where('is_send',0)
            ->where('is_look',0)
            ->select();
        if($project){
            foreach($project as $key=>$item){
                //查询用户
                $user = UserModel::find($item->user_id);
                if($user && !empty($user->openid)){
                    $wechat = new wechatCallbackapiTest();
                    // if(!isset($_SERVER['SERVER_NAME'])){
                    //    // $_SERVER['SERVER_NAME'] = 'meijing.net';
                    //     $_SERVER['SERVER_NAME'] = 'meijing.scdxtc.com';
                    // }
                   // $url = urldecode('http://'. $_SERVER['SERVER_NAME'] .'/index/message/index.html');
                 //   $url = urldecode('http://'. $_SERVER['SERVER_NAME'] .'/index/message/index.html');
                    $url = urldecode('http://meijing.scdxtc.com/inde/xmessage/index.html');
                    
                    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7f82feeff1f94fb&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=diyadaikuan#wechat_redirect";
                    $data = '{
                           "touser":"'.$user->openid.'",
                           "template_id":"Yb_k8q1RT3lVkYn3t-mJKzERfMl53rmePynMZoX8qJc",
                           "url":"'.$url.'",
                           "data":{
                                   "first": {
                                       "value":"尊敬的'."$user->user_name".':\n您的项目,'.mb_substr($item->address,0,mb_strlen($item->address)-2).'*号",
                                       "color":"#173177"
                                   },
                                   "keyword1":{
                                       "value":"'.$item->sysdate.'",
                                       "color":"#173177"
                                   },
                                   "keyword2": {
                                       "value":"项目状态:'.$item->prostatus.',积分状态:'.$item->linkstatus.'",
                                       "color":"#173177"
                                   },
                                   "remark":{
                                       "value":"感谢您的使用，祝您生活愉快！",
                                       "color":"#173177"
                                   }
                           }
                       }';
                    $wechat->tpl_send($data);
					//写入数据msg表
					MsgModel::create([
						'address'=>$item->address,
						'content'=>"项目状态:".$item->prostatus.",积分状态:".$item->linkstatus,
						'user_id'=>$user->user_id,
						'date'=>$item->sysdate,
						'created_at'=>time()
					]);
                    ProjectModel::where('id',$item->id)->update([
                       'is_send'=>1
                    ]);
                }
            }
        }
    }
    //积分发送
    public static function send_integral()
    {

        $integral = IntegralModel::where('is_send', 0)
            ->where('is_look', 0)
            ->select();
        if ($integral) {
            foreach ($integral as $k => $v) {

                //查询此用户是否存在
                $user = UserModel::find($v->user_id);
                if ($user && !empty($user->openid)) {
                    $wechat = new wechatCallbackapiTest();
                    if(!isset($_SERVER['SERVER_NAME'])){
                        //$_SERVER['SERVER_NAME'] = 'meijing.net';
                        $_SERVER['SERVER_NAME'] = 'meijing.scdxtc.com';

                    }
                 // $url = urldecode('http://'. $_SERVER['SERVER_NAME'] .'/inde/xmessage/index.html');
                    $url = urldecode('http://meijing.scdxtc.com/index/xmessage/index.html');
                    
                    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7f82feeff1f94fb&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=diyadaikuan#wechat_redirect";

                    //积分计算1:100
                    $jifen = substr($v->point,0,strlen($v->point)-3)/100;

                    $data = '{
                           "touser":"'.$user->openid.'",
                           "template_id":"sg9cmiNvXlauS5zljShwF6CeKD1mT8XRRqfATmqQIAA",
                           "url":"'.$url.'",
                           "data":{
                                   "first": {
                                       "value":"尊敬的'."$user->user_name".'",
                                       "color":"#173177"
                                   },
                                   "keyword1":{
                                       "value":"积分增加",
                                       "color":"#173177"
                                   },
                                   "keyword2": {
                                       "value":"项目:'.mb_substr($v->address,0,mb_strlen($v->address)-2).'*号",
                                       "color":"#173177"
                                   },
                                    "keyword3": {
                                       "value":"'.$jifen.'",
                                       "color":"#173177"
                                   },
                                   "remark":{
                                       "value":"感谢您的使用，祝您生活愉快！",
                                       "color":"#173177"
                                   }
                           }
                       }';


                    $re = $wechat->tpl_send($data);
					//写入数据msg表
					MsgModel::create([
						'address'=>$v->address,
						'content'=>"积分增加:".$jifen,
						'user_id'=>$user->user_id,
						'date'=>$v->sysdate,
						'created_at'=>time()
					]);
                  IntegralModel::where('id', $v->id)->update([
                        'is_send' => 1
                    ]);


                }

            }


        }
    }
    //自定义菜单
    public function meun()
    {
        $wechbat_api = new wechatCallbackapiTest();
        $access_token = $wechbat_api->get_token();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $access_token;
        $data = '{
             "button":[
              {
                   "name":"俱乐部",
                    "type":"view",
                    "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7f82feeff1f94fb&redirect_uri=http%3a%2f%2fssq.shushimall.com&response_type=code&scope=snsapi_userinfo&state=diyadaikuan#wechat_redirect"

               }
               ],
               "button":[
              {
                   "name":"使用帮助",
                    "type":"view",
                    "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7f82feeff1f94fb&redirect_uri=http%3a%2f%2fssq.shushimall.com%2findex%2fhelp%2fhelp.html&response_type=code&scope=snsapi_userinfo&state=diyadaikuan#wechat_redirect"

               }
               ],
               "button":[
              {
                   "name":"联系我们",
                    "type":"view",
                    "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7f82feeff1f94fb&redirect_uri=http%3a%2f%2fssq.shushimall.com%2findex%2fhelp%2findex.html&response_type=code&scope=snsapi_userinfo&state=diyadaikuan#wechat_redirect"

               }
               ]

         }';
        $re = $this->curl_wechat($url, $data);
        var_dump($re);
    }



    //curl
    protected function curl_date($url, $date)
    {
        //初始化
        $ch = curl_init();
        //设置请求地址
        curl_setopt($ch, CURLOPT_URL, $url);
        //捕获内容但不输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //模拟post发送
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $date);

        //执行
        $re = curl_exec($ch);
        //判断是否发送成功
        if ($re == false) {
            echo curl_error($ch);
        } else {
            echo $re;
        }
        //关闭
        curl_close($ch);
    }

    //获取assess_token
    public function get_access_token()
    {
        // $appid = 'wx703acc3701dcc383';
        // $secret = '1c9157d07bcb15c437b5986b7b52eba4';
        $appid = 'wxc7f82feeff1f94fb';
        $secret = '94abecfdad50a8609827c1c27adba840';
        $get_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $date = file_get_contents($get_url);
        $date = json_decode($date, true);

        return $date['access_token'];

    }

}
